package ace.tool.generate.code.impl.generator;

import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;

/**
 * @author caspar
 * @date 2023/11/17 9:57
 */
public abstract class AbstractBaseGenerator<Model> {

  @Getter(AccessLevel.PROTECTED)
  private final Configuration configuration;

  public static final String DATA_KEY = "model";

  protected AbstractBaseGenerator() {
    Configuration config = new Configuration(Configuration.VERSION_2_3_32);
    config.setClassForTemplateLoading(AbstractBaseGenerator.class, "/templates");
    this.configuration = config;
  }

  protected AbstractBaseGenerator(Configuration configuration) {
    this.configuration = configuration;
  }

  @SneakyThrows
  public void generate(List<Model> models) {
    models.stream().forEach(this::generate);
  }

  @SneakyThrows
  public void generate(Model model) {
    Template template = configuration.getTemplate(this.getTemplateFile());
    Map<String, Object> data = new HashMap<>();
    data.put(DATA_KEY, model);
    String fileFullName = this.getFileFullName(model);
    FileUtils.forceMkdir(new File(fileFullName).getParentFile());
    FileWriter fileWriter = new FileWriter(fileFullName);
    template.process(data, fileWriter);
  }

  protected abstract String getTemplateFile();

  protected abstract String getFileFullName(Model model);
}
